import { createZodSchema } from '@/utils/create-zod-schema'

// 1. 基础使用示例
const basicSchema = createZodSchema({
  type: 'string',
  required: true,
  min: 3,
  requiredMessage: '此项必填'
})

// 验证数据
try {
  const result = basicSchema.parse('abc')  // 通过验证
  basicSchema.parse('')  // 抛出错误：此项必填
} catch (error) {
  console.error(error.errors)
}

// 2. 表单验证示例
const loginFormSchema = createZodSchema({
  type: 'object',
  shape: {
    username: {
      type: 'string',
      required: true,
      min: 3,
      max: 20,
      requiredMessage: '请输入用户名'
    },
    password: {
      type: 'string',
      required: true,
      min: 6,
      requiredMessage: '请输入密码'
    },
    rememberMe: {
      type: 'boolean',
      required: false
    }
  }
})

// 3. 与 Vue 表单结合使用
const validateForm = (formData: any) => {
  try {
    const validData = loginFormSchema.parse(formData)
    // 验证通过，可以提交表单
    submitForm(validData)
  } catch (error) {
    // 处理验证错误
    const formErrors = error.errors.map((err: any) => ({
      field: err.path.join('.'),
      message: err.message
    }))
    handleFormErrors(formErrors)
  }
}

// 4. 复杂表单验证示例
const userProfileSchema = createZodSchema({
  type: 'object',
  shape: {
    // 基本信息
    basicInfo: {
      type: 'object',
      shape: {
        name: {
          type: 'string',
          required: true,
          min: 2,
          requiredMessage: '请输入姓名'
        },
        email: {
          type: 'string',
          email: true,
          required: true,
          customError: '请输入有效的邮箱地址'
        },
        phone: {
          type: 'string',
          regex: /^1[3-9]\d{9}$/,
          customError: '请输入有效的手机号'
        }
      }
    },
    
    // 工作经历（数组验证）
    workExperience: {
      type: 'array',
      min: 1,
      items: {
        type: 'object',
        shape: {
          company: {
            type: 'string',
            required: true,
            requiredMessage: '请输入公司名称'
          },
          position: {
            type: 'string',
            required: true,
            requiredMessage: '请输入职位'
          },
          years: {
            type: 'number',
            min: 0,
            max: 50,
            int: true
          }
        }
      }
    },
    
    // 技能评分（数字验证）
    skills: {
      type: 'object',
      shape: {
        javascript: {
          type: 'number',
          min: 0,
          max: 100,
          int: true
        },
        typescript: {
          type: 'number',
          min: 0,
          max: 100,
          int: true
        }
      }
    }
  }
})

// 5. 与 Element Plus 表单验证结合
const validateElFormField = (rule: any, value: any, callback: any) => {
  const fieldSchema = createZodSchema({
    type: 'string',
    required: true,
    min: 3,
    requiredMessage: rule.message
  })

  try {
    fieldSchema.parse(value)
    callback()
  } catch (error) {
    callback(new Error(error.errors[0].message))
  }
}

// 6. 动态表单验证
function createDynamicSchema(formConfig: any) {
  const schemaShape: Record<string, any> = {}
  
  formConfig.fields.forEach((field: any) => {
    schemaShape[field.name] = {
      type: field.type,
      required: field.required,
      requiredMessage: field.requiredMessage,
      // 根据字段配置添加其他验证规则
      ...(field.min && { min: field.min }),
      ...(field.max && { max: field.max }),
      ...(field.pattern && { regex: new RegExp(field.pattern) }),
    }
  })

  return createZodSchema({
    type: 'object',
    shape: schemaShape
  })
}

// 7. 异步验证示例
async function validateWithAsync(formData: any) {
  const schema = createZodSchema({
    type: 'object',
    shape: {
      username: {
        type: 'string',
        required: true,
        min: 3
      }
    }
  })

  try {
    // 首先进行同步验证
    const validData = schema.parse(formData)
    
    // 然后进行异步验证（例如检查用户名是否已存在）
    const isUsernameTaken = await checkUsernameExists(validData.username)
    if (isUsernameTaken) {
      throw new Error('用户名已存在')
    }
    
    return validData
  } catch (error) {
    throw error
  }
}
